package com.iteaj.iot.client;

import com.iteaj.network.IotProtocolFactory;
import com.iteaj.network.ProtocolFactory;
import com.iteaj.network.ProtocolTimeoutStorage;
import com.iteaj.network.client.ClientComponent;
import com.iteaj.network.client.ClientMessage;
import com.iteaj.network.client.IotClient;
import org.springframework.beans.factory.InitializingBean;

public abstract class TcpClientComponent<M extends ClientMessage> implements ClientComponent<M>, InitializingBean {

    private IotClient iotClient;
    private long reconnectTime = 60;
    private IotProtocolFactory protocolFactory;

    public TcpClientComponent() { }

    @Override
    public void init(Object ...args) {
        this.getClient().init(args[0]);
    }

    @Override
    public IotClient getClient() {
        if(this.iotClient != null) {
            return this.iotClient;
        } else {
            return this.iotClient = createClient();
        }
    }

    protected abstract SocketClient createClient();

    @Override
    public IotProtocolFactory protocolFactory() {
        if(null != protocolFactory)
            return protocolFactory;

        this.protocolFactory = createProtocolFactory();
        if(this.protocolFactory instanceof ProtocolFactory) {
            ((ProtocolFactory<?>) this.protocolFactory).setDelegation(createProtocolTimeoutStorage());
        }

        return this.protocolFactory;
    }

    protected abstract IotProtocolFactory createProtocolFactory();

    protected ProtocolTimeoutStorage createProtocolTimeoutStorage() {
        return new ProtocolTimeoutStorage(getName());
    }

    /**
     * 短线重连时间间隔(秒)
     * @return
     */
    public long getReconnectTime() {
        return reconnectTime;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        getClient();
        protocolFactory();
    }
}
